package com.ext.aic.utils;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.fragment.app.FragmentActivity;

import com.ext.aic.AICApplication;
import com.ext.aic.AICManager;
import com.ext.aic.R;
import com.ext.aic.beans.NotifyUnique;
import com.ext.aic.beans.NotifyUnique_;
import com.ext.aic.beans.box.NotificationMessage;
import com.ext.aic.box.RegisterAccessibilityService;
import com.ext.aic.constants.CacheConstants;
import com.ext.aic.constants.EBusConstants;
import com.ext.aic.constants.PermissionConstants;
import com.ext.aic.events.OnAccessibilityServiceEvent;
import com.eyinfo.android_pure_utils.ebus.EBus;
import com.eyinfo.android_pure_utils.encryption.Md5Utils;
import com.eyinfo.android_pure_utils.events.Action0;
import com.eyinfo.android_pure_utils.events.Action1;
import com.eyinfo.android_pure_utils.snow.Butterfly;
import com.eyinfo.mpkv.MPLocalKV;
import com.eyinfo.storage.files.FileUtils;

import java.io.File;

import io.objectbox.query.QueryBuilder;

public class BoxUtils {

    private static volatile BoxUtils instance;

    public static BoxUtils getInstance() {
        if (instance == null) {
            synchronized (BoxUtils.class) {
                if (instance == null) {
                    instance = new BoxUtils();
                }
            }
        }
        return instance;
    }

    //region 自动回复功能
    private String autoReplyTagWithEnable = "ddf4c41bbe1f0e23";
    private String autoReplyTagWithDisable = "fe04124a537c2c26";
    private boolean autoReplyMergeDetection = false;
    private boolean autoReplyBackgroundRestricted = false;
    private Action0 autoReplyCallback;
    private int notificationCount = 0;
    private int restrictedCount = 0;

    private void accessibilityFeatureWithEnable(FragmentActivity activity, boolean isMergeDetectionNotify, Action0 callback) {
        if (isMergeDetectionNotify) {
            if (PermissionUtils.getInstance().isNotificationEnabled(activity)) {
                autoReplyBackgroundRestricted = true;
                if (PermissionUtils.getInstance().isBackgroundRestricted(activity)) {
                    if (restrictedCount == 0) {
                        restrictedCount++;
                        String title = activity.getString(R.string.warm_reminder);
                        String content = activity.getString(R.string.background_restricted_apply_tip);
                        XPopupUtils.getInstance().showConfirmDialog(AICApplication.getCurrentActivity(), title, content, false, () -> EBus.getInstance().post(EBusConstants.startRestrictedSetting, autoReplyTagWithEnable));
                    }
                } else {
                    if (callback != null) {
                        callback.call();
                    }
                }
            } else {
                if (notificationCount == 0) {
                    notificationCount++;
                    String title = activity.getString(R.string.warm_reminder);
                    String content = activity.getString(R.string.notify_permission_apply_tip);
                    XPopupUtils.getInstance().showConfirmDialog(AICApplication.getCurrentActivity(), title, content, false, () -> EBus.getInstance().post(EBusConstants.startNotificationSettings, autoReplyTagWithEnable));
                }
            }
        } else {
            if (callback != null) {
                callback.call();
            }
        }
    }

    private boolean replyActivityResultValid(int requestCode, int resultCode, Bundle bundle) {
        if (requestCode != PermissionConstants.REQUEST_CODE_ACCESSIBILITY && requestCode != PermissionConstants.REQUEST_CODE_NOTIFICATION && requestCode != PermissionConstants.REQUEST_CODE_BACKGROUND_RESTRICTED) {
            return false;
        }
        String tag = bundle.getString("tag");
        return TextUtils.equals(tag, autoReplyTagWithEnable) || TextUtils.equals(tag, autoReplyTagWithDisable);
    }

    private void autoReplyAgainVerification(FragmentActivity activity) {
        if (autoReplyMergeDetection) {
            if (autoReplyBackgroundRestricted) {
                if (PermissionUtils.getInstance().isAccessibilityServiceEnabled(activity) && PermissionUtils.getInstance().isNotificationEnabled(activity) && PermissionUtils.getInstance().isBackgroundRestricted(activity)) {
                    enableAutoReplySuccess(activity);
                }
            } else {
                if (PermissionUtils.getInstance().isAccessibilityServiceEnabled(activity) && PermissionUtils.getInstance().isNotificationEnabled(activity)) {
                    enableAutoReplySuccess(activity);
                }
            }
        } else {
            if (autoReplyBackgroundRestricted) {
                if (PermissionUtils.getInstance().isAccessibilityServiceEnabled(activity) && PermissionUtils.getInstance().isBackgroundRestricted(activity)) {
                    enableAutoReplySuccess(activity);
                }
            } else {
                if (PermissionUtils.getInstance().isAccessibilityServiceEnabled(activity)) {
                    enableAutoReplySuccess(activity);
                }
            }
        }
    }

    public void onAutoReplyActivityResult(FragmentActivity activity, Bundle bundle) {
        int requestCode = bundle.getInt("requestCode");
        int resultCode = bundle.getInt("resultCode");
        if (!replyActivityResultValid(requestCode, resultCode, bundle)) {
            return;
        }
        if (requestCode == PermissionConstants.REQUEST_CODE_ACCESSIBILITY) {
            if (PermissionUtils.getInstance().isAccessibilityServiceEnabled(activity)) {
                MPLocalKV.getInstance().put(CacheConstants.ACCESSIBILITY_STATUS_KEY, true);
                String tag = bundle.getString("tag");
                if (TextUtils.equals(tag, autoReplyTagWithDisable)) {
                    accessibilityFeatureWithEnable(activity, autoReplyMergeDetection, autoReplyCallback);
                } else {
                    autoReplyAgainVerification(activity);
                }
            } else {
                MPLocalKV.getInstance().put(CacheConstants.ACCESSIBILITY_STATUS_KEY, false);
            }
        } else if (requestCode == PermissionConstants.REQUEST_CODE_NOTIFICATION) {
            if (PermissionUtils.getInstance().isNotificationEnabled(activity)) {
                MPLocalKV.getInstance().put(CacheConstants.NOTIFICATION_STATUS_KEY, true);
                autoReplyAgainVerification(activity);
            } else {
                MPLocalKV.getInstance().put(CacheConstants.NOTIFICATION_STATUS_KEY, false);
            }
        } else if (requestCode == PermissionConstants.REQUEST_CODE_BACKGROUND_RESTRICTED) {
            if (PermissionUtils.getInstance().isBackgroundRestricted(activity)) {
                MPLocalKV.getInstance().put(CacheConstants.BACKGROUND_RESTRICTED_STATUS_KEY, true);
                autoReplyAgainVerification(activity);
            } else {
                MPLocalKV.getInstance().put(CacheConstants.BACKGROUND_RESTRICTED_STATUS_KEY, false);
            }
        }
    }

    /**
     * 启用自动回复功能
     *
     * @param context                Context
     * @param isMergeDetectionNotify 是否合并检测通知权限
     * @param callback               启用成功后回调
     */
    public void enableAutoReplyFeature(FragmentActivity activity, boolean isMergeDetectionNotify, Action0 callback) {
        //检测计数
        notificationCount = 0;
        restrictedCount = 0;
        autoReplyMergeDetection = isMergeDetectionNotify;
        autoReplyCallback = callback;
        if (PermissionUtils.getInstance().isAccessibilityServiceEnabled(activity)) {
            accessibilityFeatureWithEnable(activity, isMergeDetectionNotify, callback);
            return;
        }
        String title = activity.getString(R.string.warm_reminder);
        String content = activity.getString(R.string.accessibility_permission_apply_tip);
        XPopupUtils.getInstance().showConfirmDialog(AICApplication.getCurrentActivity(), title, content, false, () -> EBus.getInstance().post(EBusConstants.startAccessibilitySettings, autoReplyTagWithDisable));
    }

    public void enableAutoReplySuccess(Context context) {
        // TODO: 2025/3/6 自动回复定时任务
        autoReplyMergeDetection = false;
        autoReplyBackgroundRestricted = false;
        autoReplyCallback = null;
        ToastyUtils.getInstance().show(context.getString(R.string.enable_auto_reply_success));
        EBus.getInstance().post(EBusConstants.detectionAISeparateEnable);
    }
    //endregion

    //region 是否启用AI分身，需要同时判断无障碍权限、通知权限、后台限制权限
    public boolean isEnableAISeparate(Context context) {
        boolean isAccessibilityServiceEnabled = PermissionUtils.getInstance().isAccessibilityServiceEnabled(context);
        boolean isNotificationEnabled = PermissionUtils.getInstance().isNotificationEnabled(context);
        boolean isBackgroundRestricted = PermissionUtils.getInstance().isBackgroundRestricted(context);
        return isAccessibilityServiceEnabled && isNotificationEnabled && !isBackgroundRestricted;
    }
    //endregion

    //region 通知(对同一个用户，相同消息仅保留一条)
    public NotificationMessage getNotifyMessage(String user, String message) {
        NotificationMessage notificationMessage = new NotificationMessage();
        notificationMessage.setId(Md5Utils.encrypt(user).hashCode());
        notificationMessage.setUser(user);
        notificationMessage.setSessionId(getUserSessionId(user));
        notificationMessage.setMessage(message);
        notificationMessage.setStatus(0);
        notificationMessage.setReceiveTime(System.currentTimeMillis());
        return notificationMessage;
    }

    private String getUserSessionId(String user) {
        return UserUtils.getInstance().getUserId() +
                PinyinUtils.getFullPinyinLower(user, "");
    }

    public String getNotifyUnique(NotificationMessage message) {
        String builder = message.getUser() +
                message.getMessage();
        return Md5Utils.encrypt(builder);
    }

    public void saveNotifyUnique(String unique) {
        NotifyUnique notifyUnique = new NotifyUnique();
        notifyUnique.setId(Butterfly.getInstance().nextId());
        notifyUnique.setUnique(unique);
        AICManager.getInstance().insertOrUpdate(NotifyUnique.class, notifyUnique);
    }

    public boolean existsNotifyUnique(String unique) {
        int count = AICManager.getInstance().count(NotifyUnique.class, query -> {
            query.equal(NotifyUnique_.unique, unique, QueryBuilder.StringOrder.CASE_INSENSITIVE);
        });
        return count > 0;
    }
    //endregion

    public void enableAutoReplyFeature(boolean isMergeDetectionNotify) {
        EBus.getInstance().post(EBusConstants.enableAutoReplyFeature, isMergeDetectionNotify);
    }

    public void enableAccessibilityFeature(FragmentActivity activity, Action1 confirmCall) {
        if (PermissionUtils.getInstance().isAccessibilityServiceEnabled(activity)) {
            if (isEnableAISeparate(activity)) {
                EBus.getInstance().post(EBusConstants.detectionAISeparateEnable);
            }
            return;
        }
        String title = activity.getString(R.string.warm_reminder);
        String content = activity.getString(R.string.accessibility_permission_apply_tip);
        XPopupUtils.getInstance().showConfirmDialog(AICApplication.getCurrentActivity(), title, content, false, () -> {
            if (confirmCall == null) {
                EBus.getInstance().post(EBusConstants.startAccessibilitySettings, autoReplyTagWithDisable);
            } else {
                confirmCall.call(autoReplyTagWithDisable);
            }
        });
    }

    public void enableNotificationFeature(FragmentActivity activity, Action1<String> confirmCall) {
        if (PermissionUtils.getInstance().isNotificationEnabled(activity)) {
            if (isEnableAISeparate(activity)) {
                EBus.getInstance().post(EBusConstants.detectionAISeparateEnable);
            }
            return;
        }
        String title = activity.getString(R.string.warm_reminder);
        String content = activity.getString(R.string.notify_permission_apply_tip);
        XPopupUtils.getInstance().showConfirmDialog(AICApplication.getCurrentActivity(), title, content, false, () -> {
            if (confirmCall == null) {
                EBus.getInstance().post(EBusConstants.startNotificationSettings, autoReplyTagWithEnable);
            } else {
                confirmCall.call(autoReplyTagWithEnable);
            }
        });
    }

    public void enableRestrictedFeature(FragmentActivity activity, Action1<String> confirmCall) {
        if (PermissionUtils.getInstance().isBackgroundRestricted(activity)) {
            if (isEnableAISeparate(activity)) {
                EBus.getInstance().post(EBusConstants.detectionAISeparateEnable);
            }
            return;
        }
        String title = activity.getString(R.string.warm_reminder);
        String content = activity.getString(R.string.background_restricted_optimization_tip);
        XPopupUtils.getInstance().showConfirmDialog(AICApplication.getCurrentActivity(), title, content, false, () -> {
            if (confirmCall == null) {
                EBus.getInstance().post(EBusConstants.startRestrictedSetting, autoReplyTagWithEnable);
            } else {
                confirmCall.call(autoReplyTagWithEnable);
            }
        });
    }

    public File getAccessibilityScreenshotDir() {
        File cacheDir = AICApplication.getInstance().getCacheDir();
        return FileUtils.createDirectory(cacheDir, "screenshot", "accessibility");
    }

    public OnAccessibilityServiceEvent getServiceEvent() {
        return RegisterAccessibilityService.getInstance();
    }
}
